package com.sam.mybatisplus.controller;

import com.sam.mybatisplus.dto.EmailDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * @classname: EmailController
 * @description: TODO
 * @Author: sam
 * @date: 2021/7/5 18:01
 */
@RequestMapping("email")
@RestController
public class EmailController {

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.protocol}")
    private String protocol;

    @Value("${spring.mail.port}")
    private String port;

    @PostMapping("send")
    public String send(@RequestBody EmailDTO emailDTO)throws Exception{
        Properties properties = new Properties();
        properties.setProperty("mail.host", host);
        properties.setProperty("mail.smtp.starttls.enable", "true");
        //properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.auth", "true");
        //properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.port", port);
        Session session = Session.getDefaultInstance(properties);
        session.setDebug(true);

        String msg = emailDTO.getContent();
        String title = emailDTO.getTitle();

        MimeMessage message = new MimeMessage(session);
        message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
        message.setFrom(new InternetAddress(emailDTO.getFrom()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailDTO.getTo()));
        message.setSubject(title);
        message.setText(msg);
        // Transport.send(message);

        // 1.创建复合消息体
        Multipart multipart = new MimeMultipart("alternative");

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(msg);
        multipart.addBodyPart(textPart);

        MimeBodyPart html = new MimeBodyPart();
        html.setContent(msg, "text/html;charset=UTF-8");
        html.setHeader("MIME-Version", "1.0");
        multipart.addBodyPart(html);

        // 4.绑定消息对象
        message.setContent(multipart);


        Transport transport = session.getTransport();
        transport.connect(host, emailDTO.getFrom(), emailDTO.getPwd());
        //发送邮件，第二个参数为收件人
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        return "ok";
    }

}
